<template>
  <div class="order-comment">
    <el-card class="comment-card">
      <template #header>
        <div class="card-header">
          <span>订单评价</span>
        </div>
      </template>

      <!-- 商品信息 -->
      <div class="products-list">
        <div v-for="product in orderInfo.products" :key="product.productId" class="product-item">
          <el-image :src="product.image" :preview-src-list="[product.image]" class="product-image" />
          <div class="product-info">
            <h4>{{ product.productName }}</h4>
            <p class="price">¥{{ product.price }}</p>
            <p class="quantity">x{{ product.quantity }}</p>
          </div>
        </div>
      </div>

      <!-- 评价表单 -->
      <el-form
        ref="commentForm"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="comment-form"
      >
        <el-form-item label="商品评分" prop="rating">
          <el-rate
            v-model="form.rating"
            :texts="['很差', '较差', '一般', '较好', '很好']"
            show-text
          />
        </el-form-item>

        <el-form-item label="评价内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入您的评价内容，对商品的使用体验、服务态度等方面进行描述"
          />
        </el-form-item>

        <el-form-item label="上传图片">
          <el-upload
            v-model:file-list="fileList"
            :action="uploadImgUrl"
            list-type="picture-card"
            :headers="headers"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-remove="handleUploadRemove"
            multiple
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="upload-tip">
                支持jpg、png格式，单张不超过5MB，最多上传5张
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="匿名评价">
          <el-switch v-model="form.isAnonymous" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交评价</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getOrder } from '@/api/user/order'
import { commentOrder } from '@/api/user/order'
import { getToken } from '@/utils/auth'

const route = useRoute()
const router = useRouter()
const orderInfo = ref({})
const fileList = ref([])

// 表单数据
const form = ref({
  orderId: route.params.orderId,
  rating: 5,
  content: '',
  images: [],
  isAnonymous: false
})

// 表单校验规则
const rules = {
  rating: [
    { required: true, message: '请对商品进行评分', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入评价内容', trigger: 'blur' },
    { min: 10, max: 500, message: '评价内容长度在10到500个字符之间', trigger: 'blur' }
  ]
}

// 上传相关
const uploadImgUrl = import.meta.env.VITE_APP_BASE_API + '/system/comment/upload/image'
const headers = ref({ Authorization: 'Bearer ' + getToken() })

// 获取订单信息
const getOrderInfo = async () => {
  try {
    const res = await getOrder(route.params.orderId)
    if (res.code === 200) {
      orderInfo.value = res.data
    }
  } catch (error) {
    console.error('获取订单信息失败:', error)
    ElMessage.error('获取订单信息失败')
  }
}

// 上传前处理
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  if (fileList.value.length >= 5) {
    ElMessage.error('最多只能上传5张图片!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response, file) => {
  if (response.code === 200) {
    form.value.images.push(response.data)
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 移除图片
const handleUploadRemove = (file) => {
  const index = form.value.images.indexOf(file.response.data)
  if (index > -1) {
    form.value.images.splice(index, 1)
  }
}

// 提交评价
const submitForm = async () => {
  try {
    const res = await commentOrder(form.value)
    if (res.code === 200) {
      ElMessage.success('评价提交成功')
      router.push('/user/orders')
    } else {
      ElMessage.error(res.msg || '评价提交失败')
    }
  } catch (error) {
    console.error('评价提交失败:', error)
    ElMessage.error('评价提交失败')
  }
}

// 取消评价
const cancel = () => {
  router.push('/user/orders')
}

onMounted(() => {
  getOrderInfo()
})
</script>

<style lang="scss" scoped>
.order-comment {
  padding: 20px;

  .comment-card {
    .card-header {
      font-weight: bold;
    }

    .products-list {
      margin-bottom: 30px;
      padding: 20px;
      background-color: #f8f8f8;
      border-radius: 4px;

      .product-item {
        display: flex;
        align-items: center;
        padding: 10px;

        .product-image {
          width: 80px;
          height: 80px;
          object-fit: cover;
          margin-right: 20px;
        }

        .product-info {
          flex: 1;

          h4 {
            margin: 0 0 10px;
            font-size: 16px;
          }

          .price {
            color: #f56c6c;
            font-weight: bold;
            margin: 5px 0;
          }

          .quantity {
            color: #666;
          }
        }
      }
    }

    .comment-form {
      max-width: 800px;
      margin: 0 auto;

      :deep(.el-rate) {
        margin-top: 8px;
      }

      .upload-tip {
        font-size: 12px;
        color: #666;
        margin-top: 5px;
      }
    }
  }

  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 100px;
    height: 100px;
  }
}
</style> 